package com.iwms.manage.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import com.iwms.common.constant.DkdContants;
import com.iwms.common.utils.DateUtils;
import com.iwms.common.utils.uuid.UUIDUtils;
import com.iwms.manage.domain.*;
import com.iwms.manage.domain.vo.ChannelVo;
import com.iwms.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iwms.manage.mapper.VendingMachineMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 *
 * @author Sean
 * @date 2024-11-01
 */
@Service
public class VendingMachineServiceImpl implements IVendingMachineService {
    private static final Logger log = LoggerFactory.getLogger(VendingMachineServiceImpl.class);
    @Autowired
    private VendingMachineMapper vendingMachineMapper;

    @Autowired
    private IVmTypeService vmTypeService;

    @Autowired
    private INodeService nodeService;

    @Autowired
    private IChannelService channelService;

    @Autowired
    private ITaskService taskService;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public VendingMachine selectVendingMachineById(Long id) {
        return vendingMachineMapper.selectVendingMachineById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param vendingMachine 设备管理
     * @return 设备管理
     */
    @Override
    public List<VendingMachine> selectVendingMachineList(VendingMachine vendingMachine) {
        return vendingMachineMapper.selectVendingMachineList(vendingMachine);
    }

    /**
     * 新增设备管理
     *
     * @param vendingMachine 设备管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertVendingMachine(VendingMachine vendingMachine) {
        //1.新增设备
        //1-1 生成位的唯一标识，补充货道编号
        String innerCode = UUIDUtils.getUUID();
        vendingMachine.setInnerCode(innerCode);//售货机编号
        //1-2 查询售货机类型表，补充设备容量
        VmType vmType = vmTypeService.selectVmTypeById(vendingMachine.getVmTypeId());
        vendingMachine.setChannelMaxCapacity(vmType.getChannelMaxCapacity());
        //1-3 查询节点表，补充:区域、点位、合作商等信息
        Node node = nodeService.selectNodeById(vendingMachine.getNodeId());
        BeanUtils.copyProperties(node, vendingMachine, "id");//商圈类型、区域、合作商
        vendingMachine.setAddr(node.getAddress());//设备地址
        //1-4 设备状态
        vendingMachine.setVmStatus(DkdContants.VM_STATUS_NODEPLOY);//0-表示未投放（数据库有默认值，这个不写也不影响）
        vendingMachine.setCreateTime(DateUtils.getNowDate());//创建时间
        vendingMachine.setUpdateTime(DateUtils.getNowDate());//更新时间
        //1-5保存
        int result = vendingMachineMapper.insertVendingMachine(vendingMachine);
        //2.新增货道
        //2-1 声明过道集合
        List<Channel> channelList = new ArrayList<>();
        //2-2 双层for循环
        for (int i = 1; i <= vmType.getVmRow(); i++) {//外层行
            for (int j = 1; j <= vmType.getVmCol(); j++) {//内层的列
                //1-1 1-2.. 2-1 2-2..
                //2-3 封装channel对象
                Channel channel = new Channel();
                channel.setChannelCode(i + "-" + j);//货道编号
                channel.setVmId(vendingMachine.getId());//售货机id
                channel.setInnerCode(vendingMachine.getInnerCode());//售货机编号
                channel.setMaxCapacity(vmType.getChannelMaxCapacity());//货道最大容量
                channel.setCreateTime(DateUtils.getNowDate());//创建时间
                channel.setUpdateTime(DateUtils.getNowDate());//修改时间
                channelList.add(channel);
                //保存货道
                //channelService.insertChannel(channel);
                /*//货道编号：货道行号*货道列号+货道序号
                Long channelNo = (long) (i*vmType.getVmCol()+j+1);
                //货道编号：货道行号*货道列号+货道序号
                String channelCode = innerCode+"_"+channelNo;*/

            }
        }
        //2-4 批量保存
        channelService.batchInsertChannel(channelList);
//        return vendingMachineMapper.insertVendingMachine(vendingMachine);
        return result;
    }

    /**
     * 修改设备管理
     *
     * @param vendingMachine 设备管理
     * @return 结果
     */
    @Override
    public int updateVendingMachine(VendingMachine vendingMachine) {
        if (vendingMachine.getNodeId() != null) {
            //查询点位表，补充:区域、点位、合作商等信息
            Node node = nodeService.selectNodeById(vendingMachine.getNodeId());
            BeanUtils.copyProperties(node, vendingMachine, "id");//商圈类型、区域、合作商
            vendingMachine.setAddr(node.getAddress());//设备地址
        }
        vendingMachine.setUpdateTime(DateUtils.getNowDate());//更新时间
        return vendingMachineMapper.updateVendingMachine(vendingMachine);
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteVendingMachineByIds(Long[] ids) {
        return vendingMachineMapper.deleteVendingMachineByIds(ids);
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteVendingMachineById(Long id) {
        return vendingMachineMapper.deleteVendingMachineById(id);
    }

    /**
     * 根据设备编号查询设备信息
     *
     * @param innerCode
     * @return VendingMachine
     */
    @Override
    public VendingMachine selectVendingMachineByInnerCode(String innerCode) {
        return vendingMachineMapper.selectVendingMachineByInnerCode(innerCode);
    }

    /**
     * 更新货道库存
     *
     * @param innerCode
     * @param taskDetails
     * @return
     */
    @Transactional
    @Override
    public int updateChannelCapacity(String innerCode, List<TaskDetails> taskDetails) {
        Long taskType;
        // 检查 taskDetails 是否为空
        if (CollUtil.isEmpty(taskDetails)) {
            log.warn("Task details list is empty for innerCode: {}", innerCode);
            return 0;
        }else{
            Task task = taskService.selectTaskByTaskId(taskDetails.get(0).getTaskId());
            taskType = task.getProductTypeId();
        }
        log.info("taskType:{}",taskType);
        // 更新最后补货时间
        // 按照售货机编号查询货道列表
        List<Channel> channelList = channelService.selectChannelListByInnerCode(innerCode);
        if (CollUtil.isEmpty(channelList)) {
            log.warn("No channels found for innerCode: {}", innerCode);
            return 0;
        }

        // 构建集合便于批量保存
        List<Channel> channelEntityList = new ArrayList<>();
        taskDetails.forEach(details -> {
            // 通过 stream 流筛选货道，比在数据库中查询性能高
            Optional<Channel> item = channelList.stream()
                    .filter(channel -> channel.getChannelCode().equals(details.getChannelCode()))
                    .findFirst();
            if (item.isPresent()) {
                Channel channelEntity = item.get();
                // 更新货道库存
                if (channelEntity.getCurrentCapacity() == null) {
                    channelEntity.setCurrentCapacity(0L);
                }
                if(taskType.equals(2L)){
                    channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() + details.getExpectCapacity());
                }else if (taskType.equals(5L)){
                    channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() - details.getExpectCapacity());

                }
                // 更新货道最后补货时间
                channelEntity.setLastSupplyTime(DateTime.now());
                channelEntityList.add(channelEntity);
            } else {
                log.warn("Channel with code {} not found for innerCode: {}", details.getChannelCode(), innerCode);
            }
        });

        // 检查 channelEntityList 是否为空
        if (CollUtil.isEmpty(channelEntityList)) {
            log.warn("No channels found to update for innerCode: {}", innerCode);
            return 0;
        }

        return channelService.updateBatchById(channelEntityList);
    }

//
//
//
//    // 更改售货机状态
//    @Override
//    public boolean updateStatus(String innerCode, Long vmStatus) {
//
//        return vendingMachineMapper.updateStatus(innerCode, vmStatus) > 0;
//    }
//
//    @Override
//    @Transactional
//    public boolean supply(String innerCode, List<TaskDetails> details) {
//        if (innerCode == null || innerCode.isEmpty()) {
//            throw new IllegalArgumentException("Inner code cannot be null or empty");
//        }
//        if (details == null || details.isEmpty()) {
//            throw new IllegalArgumentException("Task details cannot be null or empty");
//        }
//
//        // 更新最后补货时间
//        int updateLastSupplyTimeResult = vendingMachineMapper.updateLastSupplyTime(innerCode, DateUtils.getNowDate());
//        if (updateLastSupplyTimeResult <= 0) {
//            throw new RuntimeException("Failed to update last supply time for vending machine with inner code: " + innerCode);
//        }
//
//        // 按照售货机编号查询货道列表
//        List<ChannelVo> channelList = channelService.selectChannelVoListByInnerCode(innerCode);
//        if (channelList == null || channelList.isEmpty()) {
//            throw new RuntimeException("No channels found for vending machine with inner code: " + innerCode);
//        }
//
//        for (TaskDetails taskDetails : details) {
//            boolean channelFound = false;
//            for (ChannelVo channel : channelList) {
//                if (taskDetails.getChannelCode().equals(channel.getChannelCode())) {
//                    channelFound = true;
//                    // 更新货道库存
//                    channel.setCurrentCapacity(channel.getCurrentCapacity() + taskDetails.getExpectCapacity());
//                    channel.setUpdateTime(DateUtils.getNowDate());
//                    int updateChannelResult = channelService.updateChannel(channel);
//                    if (updateChannelResult <= 0) {
//                        throw new RuntimeException("Failed to update channel with code: " + channel.getChannelCode());
//                    }
//                    break;
//                }
//            }
//            if (!channelFound) {
//                throw new RuntimeException("Channel with code " + taskDetails.getChannelCode() + " not found for vending machine with inner code: " + innerCode);
//            }
//        }
//
//        return true;
//    }

}
